package com.qf.controller;

import com.qf.entity.User;
import com.qf.enums.JxcEnum;
import com.qf.util.R;
import com.qf.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

/**
 * 作者: 王鑫
 * 项目名: jxc1
 * 时间:2019/12/4  21:20
 * 描述:
 */
@RestController
@RequestMapping("user")
//@Slf4j
public class UserController {

/*    路径
    POST   http://localhost/user/login
            ``
参数
	username=?
	password=?
``
    响应数据
            成功
    {
        "code":0,
            "msg":"成功",
            "data":null
    }
    失败
    {
        "code":错误编码,
            "msg":"错误信息",
            "data":null
    }*/

    @PostMapping("login")
    public ResultVo login(String username,String password){
        //校验参数
        System.out.println(username);
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
           // log.info("[用户登录] 参数不合法，username = {}，password = {}",username,password);
        return R.error(JxcEnum.PARAMETER_ERROR);
        }
        //调用shiro执行登录
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new UsernamePasswordToken(username,password));

        }catch (UnknownAccountException e){
            e.printStackTrace();

            return  R.error(JxcEnum.USERNAME_ERROR);

        }catch (IncorrectCredentialsException e){
            e.printStackTrace();

            return R.error(JxcEnum.PASSWORD_ERROR);

        }catch (Exception e){
            e.printStackTrace();
            return R.error(JxcEnum.NOT_KNOW_ERROR);

        }
        return R.ok();

    }

    @RequestMapping("/info")
    public ResultVo info(){

        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        if (user == null){
           // log.info("【获取真实姓名】 用户未登录！");
            return R.error(JxcEnum.USE_NOT_LOGIN);
        }

        return R.ok(user.getRealname());
    }

    @RequestMapping("logout")
    public ResultVo logout(){

        Subject subject = SecurityUtils.getSubject();

        try {
            subject.logout();
            return R.ok();
        }catch (Exception e){
            return R.error(JxcEnum.NOT_KNOW_ERROR);
        }


    }
}
